package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.folli.FolliProduct;
import com.atmilan.quartz.model.entity.folli.FolliProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceFolliProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     *
     * 构建DO对象（FOLLI）
     * @param product
     * @param skus
     * @return
     */
    public StoreProductCrmebRequest buildFolliProduct(FolliProduct product, List<FolliProductSku> skus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            List<String> imageList = JSONArray.parseArray(product.getImages(), String.class);
            // 平台原价
            BigDecimal otPrice = new BigDecimal(product.getPrice());
            // 售价
            PriceResult priceResult = priceUtil.eur2Rmb(new BigDecimal(product.getDiscount()));
            BigDecimal price = priceResult.getPrice();
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getBrand())
                    .eq(StoreBrand :: getType, ProductTypeEnum.FOLLI)
                    .last("LIMIT 1"));
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getBrand(),ProductTypeEnum.FOLLI);
            StoreBrand storeBrand = (null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) ? storeBrandService.getById(buyerStoreBrand.getSuperId()) : storeBrandService.getById(5429);

            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.FOLLI.getCode() + product.getSku();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

            List<String> colorValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);

            for(FolliProductSku sku : skus) {
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getSku()+"-"+sku.getSize());
                storeProductAttrValue.setStock(sku.getStock());
                storeProductAttrValue.setPrice(price);
                storeProductAttrValue.setImage(imageList.get(0));
                storeProductAttrValue.setCost(price);
                storeProductAttrValue.setSourceCost(price);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(otPrice);
                //发货地（欧洲）
                storeProductAttrValue.setTempId(StockAreaTempEnum.EUR.getTempId());
                List<String> suk = new ArrayList<>();
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(product.getColor())) {
                    linkedMap.put("颜色", product.getColor());
                    if(!colorValueList.contains(product.getColor())){
                        colorValueList.add(product.getColor());
                    }
                    suk.add(product.getColor());
                }
                if (StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                    if(!sizeValueList.contains(sku.getSize())){
                        sizeValueList.add(sku.getSize());
                    }
                    suk.add(sku.getSize());
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.FOLLI.getMerchantId());
            productRequest.setContent(product.getDescription());
            // 商品keyword组合 (国际编码：style_code+fabric_code+color_code)
            productRequest.setKeyword(product.getSku()+" "+product.getDesignerId());
            productRequest.setStoreInfo(product.getDescription());
            productRequest.setStoreName(product.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(3);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.FOLLI.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.FOLLI.getCode())
                    .eq(CategoryMatch::getOthCategoryId, product.getGender())
                    .eq(CategoryMatch::getOthCategoryName, product.getFirstCategory())
                    .eq(CategoryMatch::getOthCategoryType,product.getCategory())
                    .last("LIMIT 1"));
            categoryMatchService.unMatchCategory(categoryMatch,product.getGender(),product.getFirstCategory(),product.getCategory(),CategoryTypeEnum.FOLLI);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Collections.singletonList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);

            productRequest.setImage(imageList.get(0));
            productRequest.setSliderImage(product.getImages());
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.FOLLI.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setSeasonCode(product.getSeason());
            productRequest.setColorCode(product.getColor());
            productRequest.setComposition(product.getComposition());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }
    
}
